<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<%
	// request.getContextPath() 以斜线开始，不以斜线结束
	pageContext.setAttribute("APP_PATH", request.getContextPath());
%>
<!-- 
	不以'/'开头就是相对路径，以当前页面为基准
	'/'开头就是绝对路径，以上下文为基准
 -->
<link rel="stylesheet"
	href="${APP_PATH }/static/bootstrap-3.3.7-dist/css/bootstrap.min.css">
</head>
<body>
	<!-- 员工修改 -->
	<!-- 
		修改id
	 -->
	<div class="modal fade" id="empUpdateModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
	  <div class="modal-dialog" role="document">
	    <div class="modal-content">
	      <div class="modal-header">
	        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
	        <h4 class="modal-title" id="myModalLabel">员工修改</h4>
	      </div>
	      <div class="modal-body">
	      	<!-- 表单开始 -->
	      	<form class="form-horizontal">
			  <div class="form-group">
			    <label for="empName_update_input" class="col-sm-2 control-label">empName</label>
			    <div class="col-sm-10">
			      <p class="form-control-static" id="empName_update_input" name="empName"></p>
			    </div>
			  </div>
			  <div class="form-group">
			    <label for="email_update_input" class="col-sm-2 control-label">email</label>
			    <div class="col-sm-10">
			      <input type="text" name="email" class="form-control" id="email_update_input" placeholder="email">
			      <span class="help-block"></span>
			    </div>
			  </div>
			  <div class="form-group">
			    <label for="gender_update_input" class="col-sm-2 control-label">gender</label>
			    <div class="col-sm-10">
			      	<label class="radio-inline">
					  <input type="radio" name="gender" id="gender1_update_input" value="M" checked="checked"> 男
					</label>
					<label class="radio-inline">
					  <input type="radio" name="gender" id="gender2_update_input" value="F"> 女
					</label>
			    </div>
			  </div>
			  <div class="form-group">
			    <label for="dept_update_select" class="col-sm-2 control-label">deptName</label>
			    <div class="col-sm-4">
			      	<select id="dept_update_select" name="dId" class="form-control">
					</select>
			    </div>
			  </div>
			</form>
			<!-- 表单结束 -->
	      </div>
	      <div class="modal-footer">
	        <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
	        <button type="button" class="btn btn-primary" id="emp_update_btn">更新</button>
	      </div>
	    </div>
	  </div>
	</div>
	
	<!-- 员工添加 -->
	<!-- 
		修改id
	 -->
	<div class="modal fade" id="empAddModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
	  <div class="modal-dialog" role="document">
	    <div class="modal-content">
	      <div class="modal-header">
	        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
	        <h4 class="modal-title" id="myModalLabel">员工添加</h4>
	      </div>
	      <div class="modal-body">
	      	<!-- 表单开始 -->
	      	<form class="form-horizontal">
			  <div class="form-group">
			    <label for="empName_add_input" class="col-sm-2 control-label">empName</label>
			    <div class="col-sm-10">
			      <input type="text" name="empName" class="form-control" id="empName_add_input" placeholder="empName">
			      <span class="help-block"></span>
			    </div>
			  </div>
			  <div class="form-group">
			    <label for="email_add_input" class="col-sm-2 control-label">email</label>
			    <div class="col-sm-10">
			      <input type="text" name="email" class="form-control" id="email_add_input" placeholder="email">
			      <span class="help-block"></span>
			    </div>
			  </div>
			  <div class="form-group">
			    <label for="gender_add_input" class="col-sm-2 control-label">gender</label>
			    <div class="col-sm-10">
			      	<label class="radio-inline">
					  <input type="radio" name="gender" id="gender1_add_input" value="M" checked="checked"> 男
					</label>
					<label class="radio-inline">
					  <input type="radio" name="gender" id="gender2_add_input" value="F"> 女
					</label>
			    </div>
			  </div>
			  <div class="form-group">
			    <label for="dept_add_select" class="col-sm-2 control-label">deptName</label>
			    <div class="col-sm-4">
			      	<select id="dept_add_select" name="dId" class="form-control">
					</select>
			    </div>
			  </div>
			</form>
			<!-- 表单结束 -->
	      </div>
	      <div class="modal-footer">
	        <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
	        <button type="button" class="btn btn-primary" id="emp_save_btn">保存</button>
	      </div>
	    </div>
	  </div>
	</div>

	<!-- 搭建显示页面 -->
	<div class="container">
		<!-- 标题 -->
		<div class="row">
			<div class="col-md-12">
				<h1>SSM-CRUD</h1>
			</div>
		</div>
		<!-- 按钮 -->
		<div class="row">
			<div class="col-md-4 col-md-offset-8">
				<button class="btn btn-primary" id="emp_add_model_btn">新增</button>
				<button class="btn btn-danger" id="emp_delete_all_btn">删除</button>
			</div>
		</div>
		<!-- 表格 -->
		<div class="row">
			<table class="table table-hover" id="emp_table">
				<thead>
					<tr>
					<th><input type="checkbox" id="check_all"></th>
					<th>#</th>
					<th>empName</th>
					<th>gender</th>
					<th>email</th>
					<th>deptName</th>
					<th>操作</th>
				</tr>
				</thead>
				<tbody>
					<c:forEach items="${pageInfo.list }" var="emp">
					<tr>
						<td>${emp.empId }</td>
						<td>${emp.empName }</td>
						<td>${emp.gender == "M"?"男":"女" }</td>
						<td>${emp.empId }</td>
						<td>${emp.empId }</td>
						<td>
							<button class="btn btn-primary btn-sm">
								<span class="glyphicon glyphicon-pencil" aria-hidden="true"></span>
								编辑
							</button>
							<button class="btn btn-danger btn-sm">
								<span class="glyphicon glyphicon-trash" aria-hidden="true"></span>
								删除
							</button>
						</td>
					</tr>
				</c:forEach>
				</tbody>
			</table>
		</div>
		<!-- 分页 -->
		<div class="row">
			<!-- 分页文本信息  -->
			<div class="col-md-6" id="page_info_area"></div>
			<!-- 分页条信息 -->
			<div class="col-md-6" id="page_nav_area">
				<%-- <nav aria-label="Page navigation">
				  <ul class="pagination">
				  	<li>
				      <a href="${APP_PATH }/emps?pn=1 ">首页</a>
				    </li>
				    <c:if test="${pageInfo.hasPreviousPage }">
				  	  <li>
					      <a href="${APP_PATH }/emps?pn=${pageInfo.pageNum - 1 } " aria-label="Previous">
					        <span aria-hidden="true">&laquo;</span>
					      </a>
					  </li>
				  	</c:if>
				    <c:forEach items="${pageInfo.navigatepageNums }" var="page_Num">
				    	<c:if test="${page_Num == pageInfo.pageNum }">
				    		<li class="active"><a href="#">${page_Num }</a></li>
				    	</c:if>
				    	<c:if test="${page_Num != pageInfo.pageNum }">
				    		<li><a href="${APP_PATH }/emps?pn=${page_Num }">${page_Num }</a></li>
				    	</c:if>
				    </c:forEach>
				    <c:if test="${pageInfo.hasNextPage }">
					      <li>
						      <a href="${APP_PATH }/emps?pn=${pageInfo.pageNum + 1 } " aria-label="Next">
						        <span aria-hidden="true">&raquo;</span>
						      </a>
						  </li>
				  	</c:if>
				    <li>
				      <a href="${APP_PATH }/emps?pn=${pageInfo.pages } ">末页</a>
				    </li>
				  </ul>
				</nav> --%>
			</div>
		</div>
	</div>
</body>
<script src="${APP_PATH }/static/js/jquery-3.2.1.min.js"></script>
<script
	src="${APP_PATH }/static/bootstrap-3.3.7-dist/js/bootstrap.min.js"></script>
<script type="text/javascript">

	var totalRecord ,currentPage;
		
	$(function(){
		to_page(1)
	})
	
	function to_page(pn){
		$.ajax({
			url: `${APP_PATH }/empsx`,
			data: `pn=` + pn,
			type: 'get',
			success:function(rs){
				// console.log(rs)
				build_emps_table(rs)
				build_page_info(rs)
				build_page_nav(rs)
				
				// 完成
				// 查询部门信息
				getDepts('#empUpdateModal select')
			}
		})
	}
	
	
	function build_emps_table(rs){
		// 清空
		$("#emp_table tbody").empty();
		
		var emps = rs.extend.pageInfo.list
		$.each(emps,function(index,item){
			
			// 添加删除多选框
			var checkBox = $('<td><input type="checkbox" class="click_item"></td>')
			
			// console.log(index,item)
			var empIdTd = $('<td></td>').append(item.empId)
			var empNameTd = $('<td></td>').append(item.empName)
			var genderTd = $('<td></td>').append(item.gender=="M"?"男":"女")
			var emailTd = $('<td></td>').append(item.email)
			var deptNameTd = $('<td></td>').append(item.department.deptName)
			
			// 操作按钮
			var editBtn = $('<button></button>')
								.addClass('btn btn-primary btn-sm edit-btn')
								.append($('<span></span>').addClass('glyphicon glyphicon-pencil'))
								.append('编辑')
			// 将id保存到按钮
			editBtn.attr('edit-id',item.empId)
								
			var delBtn = $('<button></button>')
								.addClass('btn btn-danger btn-sm delete-btn')
								.append($('<span></span>').addClass('glyphicon glyphicon-trash'))
								.append('删除')
			// 将id保存到按钮
			delBtn.attr('del-id',item.empId)
								
			var btnTd = $('<td></td>')
							.append(editBtn)
							.append(' ')
							.append(delBtn)
				
			$('<tr></tr>')
				.append(checkBox)
				.append(empIdTd)
				.append(empNameTd)
				.append(genderTd)
				.append(emailTd)
				.append(deptNameTd)
				.append(btnTd)
				.appendTo("#emp_table tbody")
		})
	}
	
	// 分页文本信息
	function build_page_info(rs){
		// 清空
		$("#page_info_area").empty();
		
		var pageInfo = rs.extend.pageInfo
		$('#page_info_area')
			.append(`当前`+ pageInfo.pageNum + `页, 总`+ pageInfo.pages + `页, 总共`+ pageInfo.total + `条记录`)
			
		// 全局记录总记录数
		totalRecord = pageInfo.total
		currentPage = pageInfo.pageNum
	}
	
	// 分页条信息
	function build_page_nav(rs){
		// 清空
		$("#page_nav_area").empty();
		var pageInfo = rs.extend.pageInfo
		
		var ul = $('<ul></ul>').addClass('pagination')
		var navEle = $('<nav></nav>').attr('aria-label','Page navigation')
		var firstPageLi = $('<li></li>').append($('<a></a>').append('首页').attr('href','#'))
		
		var prePageLiSpan = $('<span></span>').attr('aria-hidden','true').append('&laquo;')
		var prePageLiA = $('<a></a>').attr('href','#').attr('aria-label','Previous')
		var prePageLi = $('<li></li>').append(prePageLiA.append(prePageLiSpan))
		
		// 如果没有前一页
		if(!pageInfo.hasPreviousPage){
			firstPageLi.addClass('disabled')
			prePageLi.addClass('disabled')
		}else {
			// 添加跳转事件
			firstPageLi.click(function(){
				to_page(1)
			})
			// 添加跳转事件
			prePageLi.click(function(){
				to_page(pageInfo.pageNum - 1 )
			})
		}
		
		ul.append(firstPageLi).append(prePageLi)
		
		$.each(pageInfo.navigatepageNums,function(index,item){
			var numLi = $('<li></li>').append($('<a></a>').append(item).attr('href','#'))
			// 激活状态
			if(pageInfo.pageNum === item ){
				numLi.addClass('active')
			}
			// 添加跳转事件
			numLi.click(function(){
				to_page(item)
			})
			ul.append(numLi)
		})
		
		var nextPageLiSpan = $('<span></span>').attr('aria-hidden','true').append('&raquo;')
		var nextPageLiA = $('<a></a>').attr('href','#').attr('aria-label','Next')
		var nextPageLi = $('<li></li>').append(nextPageLiA.append(nextPageLiSpan))
		
		var lastPageLi = $('<li></li>').append($('<a></a>').append('末页').attr('href','#'))
		// 如果没有后一页
		if(!pageInfo.hasNextPage){
			nextPageLi.addClass('disabled')
			lastPageLi.addClass('disabled')
		}else {
			// 添加跳转事件
			nextPageLi.click(function(){
				to_page(pageInfo.pageNum + 1 )
			})
			
			// 添加跳转事件
			lastPageLi.click(function(){
				to_page(pageInfo.pages)
			})
		}
		
		ul.append(nextPageLi).append(lastPageLi)
		navEle.append(ul).appendTo('#page_nav_area')
	}
	
	function reset_form(ele){
		// 清空数据
		$(ele)[0].reset()
		// 清样式
		$(ele).find("*").removeClass('has-success has-error')
		$(ele).find('.help-block').text('')
	}
	
	// 员工添加
	$('#emp_add_model_btn').click(function(){
		// 表单重置
		reset_form('#empAddModal form')
		// 员工添加下拉列表
		getDepts('#empAddModal select')
		// 打开模态框
		$('#empAddModal').modal({
			backdrop: 'static'
		})
	})
	
	// 查询部门信息下拉列表
	function getDepts(ele){
		$(ele).empty()
		$.ajax({
			url: `${APP_PATH}/depts`,
			type: 'GET',
			success: function(res){
				var depts = res.extend.depts
				// console.log(res)
				
				$.each(depts,function(){
					var optionEle = $('<option></option>').append(this.deptName).attr("value",this.deptId)
					// $('#empAddModal select').append()
					optionEle.appendTo(ele)
				})
			}
		})
	}
	
	// 校验表单数据
	function validate_add_form(){
		// 校验用户名
		var empName = $('#empName_add_input').val()
		var regName = /(^[a-zA-Z0-9-]{6,16}$)|(^[\u2E80-\u9FFF]{3,5}$)/
		if(!regName.test(empName)){
			// alert('用户名6-1文英语或者3-5中文')
			show_validate_msg('#empName_add_input','error','用户名6-1文英语或者3-5中文')
			return false
		} else {
			show_validate_msg('#empName_add_input','success','用户名可用')
		}
		var email = $('#email_add_input').val()
		var regEmail = /^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/
		if(!regEmail.test(email)){
			// alert('邮箱格式不正确')
			show_validate_msg('#email_add_input','error','邮箱格式不正确')
			return false
		} else {
			show_validate_msg('#email_add_input','success','邮箱格式正确')
		}
		return true
	}
	
	// 校验规则
	function show_validate_msg(ele,status,msg){
		$(ele).parent().removeClass('has-success has-error')
		$(ele).next('span').text('')
		if( 'success' === status ){
			$(ele).parent().addClass('has-success')
			$(ele).next('span').text(msg)
		} else if( 'error' === status ) {
			$(ele).parent().addClass('has-error')
			$(ele).next('span').text(msg)
		}
		
	}
	
	$('#empName_add_input').change(function(){
		var empName = this.value
		$.ajax({
			url: `${APP_PATH}/checkuser`,
			type: 'POST',
			data: `empName=`+empName,
			success: function(res){
				var code = res.code
				var va_msg = res.extend.va_msg
				if(code === 200){
					show_validate_msg('#empName_add_input','success','用户名可用')
					$('#emp_save_btn').attr('ajax-va','success')
				}else if(code === 500) {
					show_validate_msg('#empName_add_input','error',va_msg)
					$('#emp_save_btn').attr('ajax-va','error')
				}
			}
		})
	})

	// 点击保存员工
	$('#emp_save_btn').click(function(){
		// 校验数据
		if(!validate_add_form()){
			return false
		}
		// 判断是否重命名
		if($(this).attr('ajax-va') === 'error' ) {
			show_validate_msg('#empName_add_input','error','用户名不可用')
			return false
		}
		// 保存数据
		$.ajax({
			url: `${APP_PATH}/empx`,
			type: 'POST',
			data: $('#empAddModal form').serialize(),
			success: function(res){
				var code = res.code
				if(code === 200){
					// console.log(res)
					// 1. 关闭模态框
					$('#empAddModal').modal('hide')
					// 2. 跳转
					to_page(totalRecord)
				}else {
					// 后端校验
					var errs = res.extend.errorField
					if(undefined !== errs.email){
						show_validate_msg('#email_add_input','error',errs.email)
					}
					if(undefined !== errs.empName){
						show_validate_msg('#empName_add_input','error',errs.empName)
					}
				}
			}
		})
	})
	
	// 点击修改按钮，委派给子元素
	$(document).on('click','.edit-btn',function(){
		// 查询员工信息
		getEmp($(this).attr('edit-id'))
		// 查询部门信息
		// getDepts('#empUpdateModal select')
		// 将编辑按钮的值，保存到模态框修改按钮
		// console.log(11111,$(this).attr('edit-id'))
		$('#emp_update_btn').attr('edit-id',$(this).attr('edit-id'))
		// 弹出模态框
		$('#empUpdateModal').modal({
			backdrop: 'static'
		})
	})
	
	// 点击删除按钮，委派给子元素
	$(document).on('click','.delete-btn',function(){
		empName = $(this).parents('tr').find('td:eq(2)').text()
		empId = $(this).attr('del-id')
		if(confirm('确认删除['+ empName +']吗?')){
			$.ajax({
				url: `${APP_PATH }/empx/` + empId,
				type: 'DELETE',
				success: function(res){
					// console.log(res)
					alert('处理成功')
					to_page(currentPage)
				}
			})
		}
	})
	
	// 查询员工信息
	function getEmp(id){
		var xhr = new XMLHttpRequest()
		if (window.XMLHttpRequest) { // Mozilla, Safari, IE7+ ...
		    httpRequest = new XMLHttpRequest();
		} else if (window.ActiveXObject) { // IE 6 and older
		    httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
		}
		xhr.open('GET','${APP_PATH }/empx/'+id+'?t='+Math.random())
		xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
		xhr.send()
		xhr.onload= function() {
		    if (xhr.readyState === XMLHttpRequest.DONE) {
		    	var res = JSON.parse(xhr.responseText)
		    	var emp = res.extend.emp
		    	console.log(emp)
				$('#empName_update_input').text(emp.empName)
				$('#email_update_input').val(emp.email)
				$('#empUpdateModal input[name=gender]').val([emp.gender])
				$('#dept_update_select').val([emp.dId]) 
			} else {
				alert('没用查询到数据')
			}
		    
		}
		
		
		/* $.ajax({
			url: `${APP_PATH }/empx/`+id,
			type: 'GET',
			success: function(res){
				var code = res.code
				console.log(res)
				if(code === 200){
					var emp = res.extend.emp
					$('#empName_update_input').text(emp.empName)
					$('#email_update_input').val(emp.email)
					$('#empUpdateModal input[name=gender]').val([emp.gender])
					$("#dept_update_select").find("option[value = '"+emp.dId+"']").attr("selected",true);
				}else {
					alert('没用查询到数据')
				}
			},
		    fail: function () {
		        alert('fail')
		    },
		    error: function (data) {
		        console.info("error: " + data.responseText);
		        alert('没用查询到数据:'+data.responseText)
		    }
		})  */
	}
	
	// 更新员工信息
	$('#emp_update_btn').click(function(){
		// 验证邮箱
		var email = $('#email_update_input').val()
		var regEmail = /^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/
		if(!regEmail.test(email)){
			show_validate_msg('#email_update_input','error','邮箱格式不正确')
			return false
		} else {
			show_validate_msg('#email_update_input','success','邮箱格式正确')
		}
		
		// 修改
		// tomcat请求体数据封装成map，通过getParmtter
		// put方式不会封装请求体，只有post会封装请求体
		// 方法一： POST  + '&_method=PUT'
		// 方法二：PUT + 添加管过滤器
		$.ajax({
			url: `${APP_PATH }/empx/`+$(this).attr('edit-id'),
			type: 'PUT',
			data: $('#empUpdateModal form').serialize(),
			success: function(res){
				var code = res.code
				if(code === 200){
					// 关闭模态框
					$('#empUpdateModal').modal('hide')
					// 跳转
					to_page(currentPage)
					var emp = res.extend.emp
				}else {
					alert('没用查询到数据')
				}
			}
		})
	})
	
	// 全选
	$('#check_all').click(function(){
		// 不能直接获取
		// alert($(this).attr('checked'))
		// 原生属性
		check = $(this).prop('checked')
		$('.click_item').prop('checked',check)
	})
	
	$(document).on('click','.click_item',function(){
		var length_all = $('.click_item').length
		var length = $('.click_item:checked').length
		var flag = length_all === length
		$('#check_all').prop('checked',flag)
	})
	
	$('#emp_delete_all_btn').click(function(){
		var empNames = ''
		var del_ids = ''
		$.each($('.click_item:checked'),function(){
			empNames += $(this).parents('tr').find('td:eq(2)').text()+","
			del_ids += $(this).parents('tr').find('td:eq(1)').text()+"-"
		})
		empNames = empNames.substring(0 , empNames.length-1)
		del_ids = del_ids.substring(0 , del_ids.length-1)
		if(confirm('确认删除['+ empNames +']吗?')){
			$.ajax({
				url: `${APP_PATH }/empx/`+ del_ids,
				type: 'DELETE',
				data: $('#empUpdateModal form').serialize(),
				success: function(res){
					var code = res.code
					if(code === 200){
						// 关闭模态框
						$('#empUpdateModal').modal('hide')
						// 跳转
						to_page(currentPage)
						var emp = res.extend.emp
					}else {
						alert('没用查询到数据')
					}
				}
			})
		}
	})
	
</script>
</html>